import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { GetLogger } from './common/utils/logger';
import { HttpStatus, ValidationPipe } from '@nestjs/common';
import { TransformInterceptor } from './common/interceptor/transform.interceptor';
import * as session from 'express-session';
import { apiReference } from '@scalar/nestjs-api-reference';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import {
  CorsConfig,
  NestConfig,
  SwaggerConfig,
} from './config/config.interface';
import { PrismaClientExceptionFilter } from 'nestjs-prisma';
import { ConfigService } from '@nestjs/config';
// import * as process from 'process';
import { systemInit } from './common/init/init';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // if (process.env.NODE_ENV != 'dev') {
  //   app.useLogger(GetLogger());
  // }

  app.useGlobalInterceptors(new TransformInterceptor());

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      forbidUnknownValues: false,
      whitelist: true,
      transformOptions: {
        enableImplicitConversion: false,
      },
    }),
  );

  app.use(
    session({
      secret: 'hao3304',
      resave: false,
      saveUninitialized: false,
    }),
  );

  const configService = app.get(ConfigService);
  const nestConfig = configService.get<NestConfig>('nest');
  const corsConfig = configService.get<CorsConfig>('cors');
  const swaggerConfig = configService.get<SwaggerConfig>('swagger');
  app.setGlobalPrefix('api');

  if (swaggerConfig.enable) {
    const options = new DocumentBuilder()
      .setTitle(swaggerConfig.title)
      .setDescription(swaggerConfig.description)
      .setVersion(swaggerConfig.version)
      .addBearerAuth()
      .build();

    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup(swaggerConfig.path, app, document);
  }

  if (corsConfig.enable) {
    app.enableCors();
  }

  const { httpAdapter } = app.get(HttpAdapterHost);
  app.useGlobalFilters(
    new PrismaClientExceptionFilter(httpAdapter, {
      P2000: HttpStatus.BAD_REQUEST,
      P2003: HttpStatus.BAD_REQUEST,
      P2022: HttpStatus.SERVICE_UNAVAILABLE,
      P2002: HttpStatus.CONFLICT,
      P2025: HttpStatus.NOT_FOUND,
    }),
  );
  console.log(nestConfig.port);
  systemInit();
  await app.listen(nestConfig.port);
}
bootstrap().then(() => console.log('服务启动成功！'));
